<?php
// Root-level PHP router to serve subfolder HTML templates and inject {$publish_url}
// Usage:
// - Open this file in your PHP-enabled server, e.g. http://localhost/path/to/login/index.php
// - Click a template link or use ?t=4 to render /4/index.html with the variable injected

// 1) Define the publish URL value to inject
$publish_url = 'http://36.137.134.189:8788/Index/cut_template?p_id=30421436&h_id=201866&o_id=40978066&t_id=6&t=1759151017';

// Define software name
$software_name = '柚子花茶香气活性物含量检测系统';

$root = __DIR__;

if (php_sapi_name() === 'cli-server') {
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $static = $root . $uri;
    if ($uri !== '/' && is_file($static)) {
        return false;
    }
}

// 2) Discover numeric subfolders that contain an index.html
$dirs = [];
foreach (scandir($root) as $item) {
    if ($item === '.' || $item === '..') { continue; }
    $path = $root . DIRECTORY_SEPARATOR . $item;
    if (is_dir($path) && preg_match('/^\d+$/', $item) && file_exists($path . DIRECTORY_SEPARATOR . 'index.html')) {
        $dirs[] = $item;
    }
}
sort($dirs, SORT_NUMERIC);

// 3) If a template is requested, load and serve it with variable injection
$template = isset($_GET['t']) ? $_GET['t'] : null;
if ($template !== null) {
    if (!preg_match('/^\d+$/', $template) || !in_array($template, $dirs, true)) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Template not found';
        exit;
    }

    $file = $root . DIRECTORY_SEPARATOR . $template . DIRECTORY_SEPARATOR . 'index.html';
    $content = file_get_contents($file);
    if ($content === false) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Failed to read template';
        exit;
    }

    // Replace placeholder occurrences with the publish URL, path, username, password, and software name
    // Supports patterns like {$publish_url}, {{publish_url}}, {$path}, {{path}}, {$username}, {{username}}, {$password}, {{password}}, {$software_name}, {{software_name}}
    $content = str_replace(
        ['{$publish_url}', '{{publish_url}}', '{$path}', '{{path}}', '{$username}', '{{username}}', '{$password}', '{{password}}', '{$software_name}', '{{software_name}}'],
        [$publish_url, $publish_url, '/' . $template, '/' . $template, 'ceshi', 'ceshi', '123456', '123456', $software_name, $software_name],
        $content
    );
    // Ensure relative resources resolve correctly by injecting a <base> tag pointing to the subfolder
    $baseTag = '<base href="./' . htmlspecialchars($template, ENT_QUOTES) . '/">';
    if (stripos($content, '<base ') === false) {
        if (preg_match('/<head[^>]*>/', $content)) {
            $content = preg_replace('/<head([^>]*)>/', '<head$1>' . $baseTag, $content, 1);
        } elseif (stripos($content, '</head>') !== false) {
            $content = preg_replace('/<\/head>/', $baseTag . '</head>', $content, 1);
        } else {
            // No head tag found; prepend base as a fallback
            $content = $baseTag . $content;
        }
    }

    header('Content-Type: text/html; charset=utf-8');
    echo $content;
    exit;
}

// 4) No template selected: render a simple index page listing all available templates
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>登录模板预览</title>
  <style>
    :root { color-scheme: light dark; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif; margin: 0; padding: 24px; }
    h1 { margin: 0 0 12px; font-size: 20px; }
    p { margin: 0 0 24px; color: #555; }
    .grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(160px,1fr)); gap: 12px; }
    .card { border: 1px solid #e5e7eb; border-radius: 10px; padding: 14px; background: #fff; box-shadow: 0 1px 2px rgba(0,0,0,0.06); }
    .card .num { font-weight: 600; margin-bottom: 6px; }
    .card a { display: inline-block; padding: 8px 10px; border-radius: 8px; text-decoration: none; color: #0a66c2; font-weight: 600; border: 1px solid #cfe2f3; background: #f6fbff; }
    .tip { margin-top: 18px; font-size: 13px; color: #666; }
  </style>
</head>
<body>
  <h1>登录模板预览</h1>
  <p>点击下面的模板卡片进行预览（已自动为变量 {$publish_url} 注入目标链接）。</p>
  <div class="grid">
    <?php foreach ($dirs as $d): ?>
      <div class="card">
        <div class="num">模板 <?php echo htmlspecialchars($d, ENT_QUOTES); ?></div>
        <a href="?t=<?php echo urlencode($d); ?>">打开</a>
      </div>
    <?php endforeach; ?>
  </div>
  <div class="tip">也可直接访问：index.php?t=4（将 4 替换为目标模板编号）。</div>
</body>
</html>